#include <math.h>
#include <dalelib/graphics/cubemap.h>
#include <dalelib/utils/daleassert.h>

namespace dalelib
{

bool Cubemap::very_first = true;


int Cubemap::loadFace(const string _Name,const int _Face)
{
	if( _first ) { _first = false; glGenTextures( 1, &_handle ); }

	ILuint il_id;
	ilGenImages( 1, &il_id );
	ilBindImage( il_id );
	ILboolean success = ilLoadImage( _Name.c_str() );

	if( success )
	{
		_width = ilGetInteger(IL_IMAGE_WIDTH);
		_height = ilGetInteger(IL_IMAGE_HEIGHT);
		_bytes_per_pixel = ilGetInteger(IL_IMAGE_BPP);
		_image_format = ilGetInteger(IL_IMAGE_FORMAT);

//			ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
		bind();

        glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_GENERATE_MIPMAP, GL_TRUE);

//		gluBuild2DMipmaps(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT+_Face, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
//        glCompressedTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());

		ilDeleteImages( 1, &il_id );
		return 0;
	}
	else
	{
		ilDeleteImages( 1, &il_id );
		return -1;
	}
}

int Cubemap::load(const string _Name,const string _Extension)
{
	loadFace( _Name+string("_positive_x.")+_Extension, 0 );
	loadFace( _Name+string("_negative_x.")+_Extension, 1 );
	loadFace( _Name+string("_positive_y.")+_Extension, 2 );
	loadFace( _Name+string("_negative_y.")+_Extension, 3 );
	loadFace( _Name+string("_positive_z.")+_Extension, 4 );
	loadFace( _Name+string("_negative_z.")+_Extension, 5 );
}

void Cubemap::bind()
{
	glEnable(GL_TEXTURE_CUBE_MAP_ARB);
	glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, _handle);
}

void Cubemap::unbind()
{
	glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);
//	glDisable(GL_TEXTURE_2D);
}

} // namespace dalelib
